import os

try:
    os.chdir(__file__[0:__file__.rfind('\\')])
except:
    ...

import requests
import json
import time
from logging import *
from configobj import ConfigObj as conf

from lib.config import *
from lib.rainmeter import *

from lib.get_zipcode import get_zipcode
from lib.get_image import process, clear

basicConfig(
    level=0,
    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
    filename="log",
    filemode="a",
    encoding='UTF-8'
)

print("OpenMapWeather设定程序")

print(f"加载 Key {config['Key']}")
info(f"加载 Key {['Key']}")

print("搜索目标地区,支持模糊搜索")
city = input("City > ")

info(f"搜索地区 {city}")

try:
    data = requests.get(f"https://geoapi.qweather.com/v2/city/lookup?location={city}&key={key}")
except requests.ConnectionError:
    error("Disconnect from the Internet")
    print("网络未连接")
    config.write()
    os.system("pause")
    os._exit(-1)

if not data.ok:
    error(f"搜索地区时遇到问题 {data}")
    os.system("pause")
    os._exit()

data = data.content
data = data.decode("UTF-8", "ignore")

data = json.loads(data)

if data["code"] != "200":
    error(f"搜索地区结果出现问题 Data: \n {data}")
    print(f"搜索地区结果出现问题 Data: \n {data}")
    os.system("pause")
    os._exit(0)

for i in range(0, len(data['location'])):
    now = data['location'][i]
    print(f"[{i}] {now['country']} {now['adm1']} {now['adm2']} {now['name']}")
    info(f"找到地区 {now['country']} {now['adm1']} {now['adm2']} {now['name']}")

print("选择(地区名与城市名相同则指代整个城区)")
choice = int(input("ID > "))

choice = data['location'][choice]

print(f"选择了地区{choice['name']}")
print(f'''
城市代码 {choice["id"]}
经度/纬度 {choice['lon']} {choice['lat']}
地区评分 {choice['rank']}
''')
info(f"选择了地区{choice['name']}")

data = Rainmeter()

data["TargetArea"] = choice['name']
data["TargetCity"] = choice['adm2']
data["TargetProvince"] = choice['adm1']
data["ID"] = choice['id']
data['lon'] = choice['lon']
data['lat'] = choice['lat']

if choice['country'] == "中国":
    data['zipcode'] = get_zipcode(choice['adm1'], choice['adm2'], choice['name'])
else:
    info("选择了外国地区，无法提供地图服务")
    print("选择了外国地区，无法提供地图服务")
    data['zipcode'] = "oversea"


info("将选择的数据写入了配置文件")
print("将选择的数据写入了配置文件")

if data['zipcode'] != 'oversea':
    process(data['zipcode'])
    info("成功更新了图片")
    print("成功更新了图片")
else:
    clear()

with open("temp/m_lock", 'w') as f:
    f.write("null")

with open("temp/d_lock", 'w') as f:
    f.write("null")


print("设定完毕")
os.system("pause")